
#Requires -Version 3
#Requires -RunAsAdministrator

<#
.SYNOPSIS 
Hydration Script

.DESCRIPTION
Hydration Environment for MDT

.NOTES
Copyright Keith Garner (KeithGa@DeploymentLive.com), All rights reserved.

For automation, you may pass in a hashtable of Key Value pairs.

.LINK
http://MDTEx.CodePlex.com

#>

[CmdletBinding()]
param(
    [HashTable] $ConfigBlock
)

function Resolve-Error ($ErrorRecord=$Error[0])
{
   $ErrorRecord | Format-List * -Force
   $ErrorRecord.InvocationInfo |Format-List *
   $Exception = $ErrorRecord.Exception
   for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException))
   {
       "$i" * 10
       $Exception |Format-List * -Force
   }
}

write-verbose "Load Library Modules $PSScriptRoot\Module\MDTEx"
Import-Module "$PSScriptRoot\Module\MDTEx" -ArgumentList ($PSBoundParameters['Verbose'] -eq $true) | out-string | write-verbose

if (-not (test-path Variable:logpath)) { set-LogPath "$PSScriptRoot\Hydrate.log" }
">>>>>>>>>>> Start Hydration" | Write-LogVerbose

if ( $ConfigBlock.contains("HydrationScripts") )
{
    $HydrationScripts = $ConfigBlock.HydrationScripts
}
else
{
    "Enumerate through all *.MDTEx.PS1 scripts." | Write-LogVerbose

    $HydrationScripts  = @()
    $HydrationScripts += get-childitem -recurse -path $PSScriptRoot -Include "*.mdt.ps1" -Exclude "*.Optional.mdt.ps1"
    $HydrationScripts += get-childitem -recurse -path $PSScriptRoot -Include "*.Optional.mdt.ps1" | Out-GridView -OutputMode Multiple
}

foreach ( $FileItem in $HydrationScripts )
{
    ">"*80 + "`r`n>    Run Command $($FileItem.FullName)`r`n" + ">"*80 | Write-LogVerbose
    try
    {
        & $($FileItem.FullName) @ConfigBlock
    }
    catch
    {
         Resolve-Error | out-string | Write-LogError
        $_.Exception | Write-Warning
        break
    }
}

">>>>>>>>>>> Finished Hydration" |Write-LogVerbose
